<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,user-scalable=no" />
		<title></title>
        <style>
        	#box{
        		width: 100px;
        		height: 100px;
        		background: pink;
        		position: absolute;
        	}
        </style>
	</head>
	<body>
<div id="box"></div>
<script>
var oBox=document.querySelector("#box");
oBox.onmousedown=function(ev){ //设置box1捕获所有的鼠标按下的事件
	var e=ev||event;
	var disX=e.clientX-oBox.offsetLeft;
	var disY=e.clientY-oBox.offsetTop;
	//兼容ie8
	//当拖动过快，或者是超出浏览器的文档窗口时，拖动对象身上的onmousedown就会失效，拖动时为拖动的元素对象锁定鼠标事件  
	//在chrome中没有setCapture()和releaseCapture()方法  ,调用会导致浏览器报错,所以要判断浏览器是否认识setCapture
	if(oBox.setCapture){ 
		oBox.setCapture();
	}

	document.onmousemove=function(ev){
		var e=ev||event;
		var L=e.clientX-disX;
		var T=e.clientY-disY;
		
		//边界：最大屏幕的总宽度-div的宽度
/*		if(L<0){
			L=0;
		}else if(L>document.documentElement.clientWidth-oBox.offsetWidth){
			L=document.documentElement.clientWidth-oBox.offsetWidth
		}
		if(T<0){
			T=0;
		}else if(T>document.documentElement.clientHeight-oBox.offsetHeight){
			T=document.documentElement.clientHeight-oBox.offsetHeight
		}
*/
        L=Math.min(Math.max(L,0),document.documentElement.clientWidth-oBox.offsetWidth)
        T=Math.min(Math.max(T,0),document.documentElement.clientHeight-oBox.offsetHeight)

		oBox.style.left=L+"px";
		oBox.style.top=T+"px";
	}
	document.onmouseup=function(){
		document.onmousemove=document.onmouseup=null;
		if(oBox.releaseCapture){
			oBox.releaseCapture();//拖动后在解除事件锁定
		}
	}
	return false;//清除浏览器拖放默认行为
}


</script>
</body>
</html>
